<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import useDialog from "@/hooks/useDialog"
import SysDialog from "@/components/dialog/SysDialog.vue"
import { getRoleDataScope,assignRoleData } from '@/api/role/index.ts'
import {RoleDataScopeParam} from "@/api/role/type.ts";

// 弹框属性
const { dialog, onShow, onClose } = useDialog()

// 树的ref
const treeRef = ref<InstanceType<typeof ElTree>>()

// 数据范围选项
const dataScopeOptions = [
  { label: '全部数据权限', value: 0 },
  { label: '自定数据权限', value: 1 },
  { label: '本部门数据权限', value: 2 },
  { label: '本部门及以下数据权限', value: 3 },
  { label: '仅本人数据权限', value: 4 }
]


// 树的属性配置
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 表单数据
const formData = reactive(<RoleDataScopeParam>{
  roleId: undefined,
  roleName: undefined,
  code:undefined,
  dataScope: 0,
  deptIds: [] as string[]
})

// 部门树数据
const deptTreeData = ref([])

// 显示弹框
const show = async (roleId: number) => {
  dialog.title = '分配数据权限'
  dialog.width = 600
  dialog.height = 400
  try {
    const res = await getRoleDataScope(roleId)
    if (res.code === 200) {
      const { id, roleName,code, dataScope, listDept, checkList } = res.data
      formData.roleId = id
      formData.roleName = roleName
      formData.code = code
      formData.dataScope = dataScope
      formData.deptIds = checkList || []
      deptTreeData.value = listDept
    }
  } catch (error) {
    console.error('获取数据权限失败:', error)
  }

  onShow()
}

// 数据范围改变
const handleDataTypeChange = (value: number) => {
  if (value !== 1) {
    formData.deptIds = []
  }
}

// 提交数据
const handleSubmit = async () => {
  try {
    // 如果是自定义数据权限，需要获取选中的部门ID
    if (formData.dataScope === 1) {
      // 选中的
      const checkedKeys = treeRef.value?.getCheckedKeys(false) as string[]
      // 半选中的
      const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() as string[]
      formData.deptIds = [...checkedKeys]

      console.log("选中的："+checkedKeys)
      console.log("半选中的："+halfCheckedKeys)
      console.log("提交数据："+formData.deptIds)
      if (formData.deptIds.length === 0) {
        ElMessage.warning('请选择部门')
        return
      }
    }

    // 分配数据权限
    await assignRoleData(formData)
    ElMessage.success('分配数据权限成功')
    onClose()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

defineExpose({
  show
})
</script>

<template>
  <SysDialog
    :title="dialog.title"
    :width="dialog.width"
    :height="dialog.height"
    :visible="dialog.visible"
    @on-close="onClose"
    @on-confirm="handleSubmit">
    <template #content>
      <el-form :model="formData" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="formData.roleName" disabled />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="formData.code" disabled />
        </el-form-item>

        <el-form-item label="数据范围">
          <el-select
            v-model="formData.dataScope"
            placeholder="请选择数据范围"
            style="width: 100%"
            filterable
            @change="handleDataTypeChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 自定义数据权限时显示部门树 -->
        <el-form-item v-if="formData.dataScope === 1" label="数据权限">
          <el-tree
            style="width: 100%"
            ref="treeRef"
            :data="deptTreeData"
            :props="defaultProps"
            show-checkbox
            default-expand-all
            node-key="id"
            :default-checked-keys="formData.deptIds"
            class="permission-tree" />
        </el-form-item>
      </el-form>
    </template>
  </SysDialog>
</template>

<style scoped lang="scss">
.permission-tree {
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-select) {
  width: 100%;
}
</style>
